package deng.ejb3.examples.simplecase.client;

import java.io.StringWriter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.bind.JAXB;

import deng.ejb3.examples.simplecase.Constants;
import deng.ejb3.examples.simplecase.Employee;
import deng.ejb3.examples.simplecase.EmployeeSampleGenerator;

public class SendCreateNewEmployeeToQueue {

	public static void main(String[] args) {
		int numOfEmployees = 1;
		if (args.length >0) {
			numOfEmployees = Integer.parseInt(args[0]);
		}
		Context ctx = null;
		Connection conn = null;		
		try {
			ctx = new InitialContext();
			Queue q1 = (Queue)ctx.lookup(Constants.CREATE_EMPLOYEE_QUEUE);
			ConnectionFactory cf = (ConnectionFactory)ctx.lookup(Constants.JMS_CONNECTION_FACTORY);
			conn = cf.createConnection();
			Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer producer = sess.createProducer(q1);
			
			EmployeeSampleGenerator sampleGenerator = new EmployeeSampleGenerator();
			
			for (int i = 0; i < numOfEmployees; i ++) {
				Employee employee = sampleGenerator.generateTestCustomer();
				StringWriter stringWriter = new StringWriter();
				JAXB.marshal(employee, stringWriter);
				
				Message msg = sess.createTextMessage(stringWriter.toString());
				producer.send(msg);
				System.out.println("Msg sent: New customer: " + employee);
			}
			
			producer.close();
			sess.close();
		} catch (Exception e) {
			throw new RuntimeException("Failed to send new customer into Q.", e);
		} finally {
			MainHelper.close(ctx);
			MainHelper.close(conn);
		}
	}

}
